<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报表名称" prop="reportName">
        <el-input v-model="queryParams.reportName" placeholder="请输入报表名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="图表类型" prop="reportType">
        <el-input v-model="queryParams.reportType" placeholder="请输入库表信息中包含的表的数量" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" size="small" @click="handleAdd"
          v-hasPermi="['report:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" size="small" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['report:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" size="small" @click="handleExport"
          v-hasPermi="['report:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报告id" align="center" prop="reportId" />
      <el-table-column label="报表名称" align="center" prop="reportName" />
      <el-table-column label="报表描述" align="center" prop="reportDesc" />
      <el-table-column label="报表生成类型" align="center" prop="genType" />
      <el-table-column label="报表数量" align="center" prop="dtNum" />
      <el-table-column label="sql语句" align="center" prop="sqlInfos" width="200" show-overflow-tooltip/>
      <el-table-column label="报表x轴" align="center" prop="showX" width="200" show-overflow-tooltip />
      <el-table-column label="报表y轴" align="center" prop="showY" width="200" show-overflow-tooltip />
      <el-table-column label="图表类型" align="center" prop="reportType" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="small" type="primary" link @click="handleUpdate(scope.row)"
            v-hasPermi="['system:report:edit']">修改</el-button>
          <el-button size="small" type="primary" link @click="handleDelete(scope.row)"
            v-hasPermi="['system:report:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="1200px" append-to-body :destroy-on-close="true"
      @closed="handleDialogClosed">
      <el-form :model="form" :rules="rules">
        <!-- 基本信息组件 -->
        <BasicInfo :form="form" />

        <!-- 库表信息组件 -->
        <TableInfo :form="form" :hasDesc="hasDesc" :dbList="dbList" :tableList="tableList"
          :loadingDb="loadingDb" :loadingTable="loadingTable"
          @view-table="handleViewTable" @delete-table="handleDeleteTable" @add-table="handleAddTable"
          @ai-generate="handleAIGenerateTable" @table-list="fetchTableList" />

        <!-- SQL编辑器组件 -->
        <SqlEditor :form="form" :hasTable="hasTable" :tableColumns="tableColumns" 
          @rule-generate="handleRuleGenerateSQL" @ai-generate="handleAIGenerateSQL"
          @validate-sql="handleValidateSQL" @sql-input="handleSqlInput" @select="handleSelect" />

        <!-- 坐标轴配置组件 -->
        <AxisConfig :available-columns="availableColumns" :operators="operators" :xColumns="xColumns"
          :yColumns="yColumns" :hasSql="hasSql" :has-xy="hasXy" @get-columns="handleGetColumns"
          @ai-generate="handleAIGenerateXY" @validate="handleValidateXY" @hand-drop="handleDrop"
          @handle-tag-change="handleTagChange" @add-column="addColumn" @remove-column="removeColumn"/>

        <!-- 图表类型配置组件 -->
        <ChartConfig :form="form" :hasXy="hasXy" :reportTypeOptions="reportTypeOptions" :chartOption="chartOption"
          @report-type-change="handleReportTypeChange" @handle-generate-chart="handleGenerateChart"/>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 表格信息查看弹窗 -->
    <el-dialog title="表格详细信息" v-model="tableViewVisible" width="800px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="表名">{{ tableInfo.tableName }}</el-descriptions-item>
        <el-descriptions-item label="表描述">{{ tableInfo.tableDesc }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="tableInfo.columns" border style="margin-top: 20px;">
        <el-table-column prop="columnName" label="列名" />
        <el-table-column prop="columnType" label="列类型" />
        <el-table-column prop="columnLength" label="列长度" />
        <el-table-column prop="columnDesc" label="列描述" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useReport } from './composables/useReport'
import BasicInfo from './components/BasicInfo.vue'
import TableInfo from './components/TableInfo.vue'
import SqlEditor from './components/SqlEditor.vue'
import AxisConfig from './components/AxisConfig.vue'
import ChartConfig from './components/ChartConfig.vue'

// 使用组合式API中的状态和方法
const {
  // 属性
  loading,
  ids,
  single,
  multiple,
  showSearch,
  total,
  reportList,
  title,
  open,
  formRef,
  queryFormRef,
  xColumns,
  yColumns,
  hasDesc,
  hasTable,
  hasSql,
  hasXy,
  typeOrder,
  tableViewVisible,
  currentTable,
  queryParams,
  form,
  rules,
  dbList,
  tableList,
  tableInfo,
  tableColumns,
  tableCache,
  loadingDb,
  loadingTable,
  chartOption,
  availableColumns,
  // 方法
  getList,
  reset,
  handleQuery,
  resetQuery,
  handleSelectionChange,
  handleDelete,
  handleExport,
  handleAdd,
  handleUpdate,
  handleDialogClosed,
  fetchTableList,
  handleDbChange,
  handleViewTable,
  handleAIGenerateTable,
  handleRuleGenerateSQL,
  handleAIGenerateSQL,
  handleValidateSQL,
  handleSqlInput,
  handleSelect,
  handleGetColumns,
  handleAIGenerateXY,
  handleValidateXY,
  handleGenerateChart,
  submitForm,
  cancel,
  addColumn,
  removeColumn,
  updateIndex,
  updateType,
  handleTagChange,
  handleDrop,
  handleAddTable,
  handleDeleteTable,
  handleReportTypeChange
} = useReport()

// 可选列数据
// const availableColumns = ref([
//   { label: '股票代码', value: 'stockCode', type: 'string' },
//   { label: '股票名称', value: 'stockName', type: 'string' },
//   { label: '开盘价', value: 'openPrice', type: 'number' },
//   { label: '收盘价', value: 'closePrice', type: 'number' },
//   { label: '最高价', value: 'highPrice', type: 'number' },
//   { label: '最低价', value: 'lowPrice', type: 'number' },
//   { label: '成交量', value: 'volume', type: 'number' },
//   { label: '成交额', value: 'amount', type: 'number' }
// ])

// 操作符数据
const operators = ref([
  { label: '+', value: '+', type: 'op' },
  { label: '-', value: '-', type: 'op' },
  { label: '*', value: '*', type: 'op' },
  { label: '/', value: '/', type: 'op' },
  { label: 'sum', value: 'sum', type: 'op' },
  { label: 'avg', value: 'avg', type: 'op' },
  { label: 'count', value: 'count', type: 'op' },
  { label: 'max', value: 'max', type: 'op' },
  { label: 'min', value: 'min', type: 'op' },
  { label: '(', value: '(', type: 'op' },
  { label: ')', value: ')', type: 'op' },
  { label: '[', value: '[', type: 'op' },
  { label: ']', value: ']', type: 'op' },
  { label: '{', value: '{', type: 'op' },
  { label: '}', value: '}', type: 'op' },
  { label: '_', value: '_', type: 'string_op' }
])

// 报表类型选项
const reportTypeOptions = ref([
  { label: '柱状图', value: 'bar' },
  { label: '折线图', value: 'line' },
  { label: '饼图', value: 'pie' },
  { label: '散点图', value: 'scatter' }
])

// 监听表单数据变化
watch(() => form.reportDesc, (newVal) => {
  hasDesc.value = !!newVal
})

watch(() => form.tableInfos, (newVal) => {
  hasTable.value = newVal && newVal.length > 0
}, { deep: true })

watch(() => form.sqlInfos, (newVal) => {
  hasSql.value = !!newVal
})

// 在watch部分添加
watch(() => [form.xColumns, form.yColumns], () => {
  // 判断xColumns和yColumns是否有数据
  // 如果有数据，hasXy的值为true
  // 如果没有数据，hasXy的值为false
  // 注意：这里使用了可选链操作符，确保form.xColumns和form.yColumns不为null或undefined

  if (form.xColumns?.length > 0 && form.yColumns?.length > 0) {
    let hasX = false
    let hasY = false
    for (let i = 0; i < form.xColumns.length; i++) {
      if (form.xColumns[i].values.length > 0) {
        hasX = true
        break
      }
    }
    for (let i = 0; i < form.yColumns.length; i++) {
      if (form.yColumns[i].values.length > 0) {
        hasY = true
        break
      }
    }
    hasXy.value = hasX && hasY
  }
}, { deep: true })

// 监听图表类型变化
watch(() => form.reportType, (newVal) => {
  if (newVal) {
  }
})

// 初始化
getList()
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: center;
}
</style>
